package org.longsheng.GroovyLearn.controller;

import groovy.util.logging.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;

@RestController
@RequestMapping("/test2/")
@Slf4j
public class Test2Controller {
    @GetMapping("test1")
    public String test1() {
        MyClosure c = new MyClosure() {
            @Override
            void call(Object o) {
                System.out.println(String.valueOf(o));
            }
        };
        c.call("text");

        return "hi，test1";
    }

    static boolean callMethod(Object o, String method, Object... args) {
        try {
            Method func = o.getClass().getDeclaredMethod(method);
        } catch (Exception ignored) {
            System.out.println(ignored.getMessage()+":"+ignored.getStackTrace());
        }

        return false;
    }

    @GetMapping("test2")
    public String test2() {
        MyClosure2 c = new MyClosure2() {
            @Override
            void call() {
                if (!callMethod(this, "func")) {
                    callMethod(delegate, "func");
                }
            }
        };
        c.delegate = new MyDelegate();
        c.call();

        return "hi，test2";
    }

    abstract class MyClosure2 {
        Object delegate;
        abstract void call();
    }

    class MyDelegate {
        void func() {
            System.out.println("func");
        }
    }

    abstract class MyClosure {
        abstract void call(Object o);
    }
}

